package com.example.distributionlock;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

@Service
public class LockService {
    private static final long LOCK_EXPIRE = 30_000;
    private static final Logger LOGGER = LoggerFactory.getLogger(LockService.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    @Qualifier("lock")
    private RedisScript<Boolean> lockScript;

    @Autowired
    @Qualifier("unlock")
    private RedisScript<Boolean> unlockScript;

    @Autowired
    @Qualifier("refresh")
    private RedisScript<Boolean> refreshScript;

    public boolean lock(String key, String value) {
        boolean res = redisTemplate.execute(lockScript, List.of(key), value, LOCK_EXPIRE);
        if (res == false) {
            return false;
        }
        refresh(key, value);
        LOGGER.info("lock, key: {}, value: {}, res: {}", key, value, res);
        return res;
    }

    public boolean unlock(String key, String value) {
        Boolean res = redisTemplate.execute(unlockScript, List.of(key), value);
        LOGGER.info("unlock, key: {}, value: {}, res: {}", key, value, res);
        return res != null && Boolean.TRUE.equals(res);
    }


    private void refresh(String key, String value) {
        Thread t = new Thread(() -> {
            while (true) {
                redisTemplate.execute(refreshScript, List.of(key), value, LOCK_EXPIRE);
                try {
                    Thread.sleep(LOCK_EXPIRE / 2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                LOGGER.info("refresh, current time: {}, key: {}, value: {}", System.currentTimeMillis(), key, value);
            }
        });
        t.setDaemon(true); // 守护线程
        t.start();
    }

}
